import base64
import hashlib
import hmac
import json
import time
import urllib.parse

import requests


def webhook_url(secret, webhook):
    timestamp = str(round(time.time() * 1000))
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote(base64.b64encode(hmac_code))
    _url = webhook + "&timestamp={timestamp}&sign={sign}".format(timestamp=timestamp, sign=sign)
    return _url


def get_prices(symbols):
    url = "https://bnapi.bnlex.top/fapi/fapi/v1/klines"
    prices = {}

    for symbol in symbols:
        params = {
            'symbol': symbol,
            'interval': '1m',
            'limit': 100
        }

        try:
            # 发送GET请求
            response = requests.get(url, params=params)

            # 如果请求成功
            if response.status_code == 200:
                data = response.json()

                # 获取最新K线数据（最后一条数据）
                latest_kline = data[-1]

                # 最新价格为K线数据中的收盘价 (close price)
                latest_price = float(latest_kline[4])  # [4] 是收盘价的索引
                prices[symbol] = latest_price
            else:
                print(f"请求失败，状态码: {response.status_code}，交易对: {symbol}")
        except Exception as e:
            print(f"发生错误: {e}，交易对: {symbol}")

    return prices


def send_dingtalk_message(prices):
    webhook = 'https://oapi.dingtalk.com/robot/send?access_token=618a59eb95cd08ad623099b6a0e165eb2b64a04a3a27f320bd89ffe8f62740dc'
    secrets = 'SECbee0492092c062770479739ca9f3f8fb539e0bbc6535b00e5b9f690aa06be9fc'

    # 生成钉钉消息签名
    url = webhook_url(secrets, webhook)

    # 格式化消息内容，确保价格信息之间换行
    price_details = "\n\n".join([f"**{symbol}** : `{price:.2f}`" for symbol, price in prices.items()])
    link = "点击查看详细信息：[价格详情](https://space.coze.cn/web?task_id=7535407402910335232&is_shared=1&uri=7535407402910335232%2F%E5%8A%A0%E5%AF%86%E8%B4%A7%E5%B8%81%E7%BD%91%E9%A1%B5%E4%BF%AE%E5%A4%8D-6805a139b1.html&share_id=7535412317371449635&secret=22njCNW2&from=realtime)"

    message = {
        "msgtype": "markdown",
        "markdown": {
            "title": "最新交易对价格",
            "text": f"## 币安永续价格(不是现货价格)\n\n{price_details}\n\n---\n\n{link}"
        }
    }

    # 发送请求
    headers = {'Content-Type': 'application/json'}
    response = requests.post(url, data=json.dumps(message), headers=headers, timeout=(10, 10))

    if response.status_code == 200:
        print("钉钉通知发送成功")
    else:
        print(f"钉钉通知发送失败，状态码: {response.status_code}")


def print_prices_periodically(symbols, interval=300):
    while True:
        # 记录当前时间
        start_time = time.time()

        # 获取所有交易对的价格
        prices = get_prices(symbols)

        if prices:
            print("\n最新价格：")
            for symbol, price in prices.items():
                print(f"{symbol} 最新价格: {price:.2f}")

            # 发送钉钉通知
            send_dingtalk_message(prices)
        else:
            print("无法获取最新价格")

        # 计算下次执行时间
        elapsed_time = time.time() - start_time
        sleep_time = interval - elapsed_time

        if sleep_time > 0:
            print(f"\n下一次更新时间将在 {sleep_time // 60} 分钟后...")
            time.sleep(sleep_time)
        else:
            print("任务执行时间超出预期，立即进行下一轮...")
            time.sleep(1)  # 如果任务执行时间大于间隔，立刻继续下次执行


# 交易对列表
symbols = ["BTCUSDT", "ETHUSDT", "BNBUSDT", "SOLUSDT", "PAXGUSDT"]

# 启动定时打印价格
# print_prices_periodically(symbols)
